from sqlalchemy.orm import Session
from models.consultation_model import Consultation
from schemas.consultation_schemas import ConsultationCreate, ConsultationUpdate
from fastapi import HTTPException

def get_consultation(db: Session, consultation_id: int):
    db_consultation = db.query(Consultation).filter(Consultation.ID == consultation_id).first()
    if not db_consultation:
        raise HTTPException(status_code=404, detail="Consultation not found")
    return db_consultation

def get_consultations(db: Session, skip: int = 0, limit: int = 100):
    return db.query(Consultation).offset(skip).limit(limit).all()

def create_consultation(db: Session, consultation: ConsultationCreate):
    db_consultation = Consultation(
        doctor_ID=consultation.doctor_ID,
        patient_ID=consultation.patient_ID,
        con_date=consultation.con_date,
        result=consultation.result.model_dump(),
    )
    db.add(db_consultation)
    db.commit()
    db.refresh(db_consultation)
    return db_consultation

def update_consultation(db: Session, consultation_id: int, consultation: ConsultationUpdate):
    db_consultation = get_consultation(db, consultation_id)
    update_data = consultation.dict(exclude_unset=True)
    for key, value in update_data.items():
        setattr(db_consultation, key, value)
    db.add(db_consultation)
    db.commit()
    db.refresh(db_consultation)
    return db_consultation

def delete_consultation(db: Session, consultation_id: int):
    db_consultation = get_consultation(db, consultation_id)
    db.delete(db_consultation)
    db.commit()
    return {"message": "Consultation deleted successfully"}

def get_consultations_by_patient(db: Session, patient_id: int):
    """
    根据病人ID获取所有相关咨询记录
    """
    return db.query(Consultation).filter(Consultation.patient_ID == patient_id).all()

def get_consultations_by_doctor(db: Session, doctor_id: int):
    """
    根据医生ID获取记录
    """
    return db.query(Consultation).filter(Consultation.doctor_ID == doctor_id).all()